package qf.sail.controller;

import qf.sail.dao.impl.OrderDaoImpl;
import qf.sail.entity.Account;
import qf.sail.entity.Order;
import qf.sail.service.GoodService;
import qf.sail.service.OrderService;
import qf.sail.service.impl.GoodServiceImpl;
import qf.sail.service.impl.OrderServiceImpl;
import qf.sail.util.Alipay;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/aliPayNotify")
public class AliPayNotifyServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        OrderService orderService = new OrderServiceImpl();
        GoodService goodService = new GoodServiceImpl();

        System.out.println("进入支付宝异步通知");

        if(!Alipay.isValid(req)){
            System.out.println("支付宝异步通知签名验证失败!");
            resp.getWriter().write("fail");
            return;
        }
        //签名验证通过
        //商户订单号
        String sn = req.getParameter("out_trade_no");
        //支付宝交易金额
        String total_amount = req.getParameter("total_amount");
        //交易状态
        String trade_status = req.getParameter("trade_status");

        Order order = orderService.getOrderBySn(sn);

        if(order == null){
            resp.getWriter().write("fail");
            System.out.println("返回订单号不正确");
            return;
        }

        if("TRADE_SUCCESS".equals(trade_status)){
            //支付成功，处理业务
            System.out.println("订单号:"+sn+",支付成功，支付了!"+total_amount+"元");
            resp.getWriter().write("success");
            //更新订单状态
            orderService.updateOrderStatus(OrderServiceImpl.IS_PAY,order.getId());
            //更新商品信息
            goodService.updateGood(order.getId());
            return;
        }
        System.out.println("支付失败");
        resp.getWriter().write("fail");

    }
}
